import axios from '../js_sdk/xtshadow-axios/axios.min'
import store from '../store'
import { paramsToStr, toLogin } from './tools'
import Cache from './cache'
import BASE_URL from './path'
import { router } from '../router'

function checkParams(params) {
	if (typeof params != 'object') return params
	for (let key in params) {
		const value = params[key];
		if (value === null || value === undefined || value === "") {
			delete params[key];
		}
	}
	return params;
}


const service = axios.create({
	baseURL: BASE_URL.api + '/',
	timeout: 10000,
	header: {
		'content-type': 'application/json'
	}
});

// request拦截器
service.interceptors.request.use(
	config => {
		config.params = checkParams(config.params)
			// console.log(config.params);
		if (config.method == 'GET') {
			config.url += paramsToStr(config.params)
		}
		
		// console.log('Token',uni.getStorageSync('TOKEN'));
		config.header.Authorization = "Bearer " + store.getters.token
		return config
	},
	error => {
		// Do something with request error
		//console.log(error) // for debug
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	async (response) => {
			if (response.data) {
			    // console.log(response);
				 const { status_code } = response.data;
				 // console.log(status_code);
				 if( status_code == 401) {
					 // console.log(response);
					 store.commit('logout')
					 toLogin()
				 } else if (status_code == 200) {
					  return Promise.resolve(response.data)
				 } else {
					  uni.showToast({
						title:response.data.msg,
						icon:'none'
					 })	
				 }
			}
		},
		error => {
			// uni.showToast({
			// 	title: "系统错误",
			// 	icon: "none"
			// })
			console.log(error)
			console.log('err' + error) // for debug
			return Promise.reject(error)
		}
)


export default service